#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <fstream>
#include <unordered_map>

#include "Log.hpp"

using namespace log_ns;

const std::string sep = ": ";

class Dict
{
private:
    void loaddict(const std::string &dict_path)
    {
        std::ifstream in(dict_path);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s failed!\n", dict_path.c_str());
            exit(1);
        }

        std::string line;
        while (std::getline(in, line))
        {
            std::cout << "---------------" << std::endl;

            LOG(DEBUG, "load info : %s , success\n", line.c_str());
            if (line.empty())
                continue;
            auto pos = line.find(sep);
            if (pos == std::string::npos)
                continue;

            std::string key = line.substr(0, pos);
            if (key.empty())
                continue;
            std::string value = line.substr(pos + sep.size());
            if (value.empty())
                continue;

            _dict.insert(std::make_pair(key, value));
        }
        LOG(INFO, "load %s done\n", dict_path.c_str());
        in.close();
    }

public:
    Dict(const std::string &dict_path)
        : _path(dict_path)
    {
        loaddict(dict_path);
    }

    std::string Translate(std::string &words)
    {
        if (words.empty())
            return "None";

        size_t i;
        std::string echo_str;
        std::string word;
        do
        {
            i = words.find(' ');
            if (i != std::string::npos)
                word = words.substr(0, i);
            else
                word = words.substr(0, words.size() - 2);
            words.erase(0, i + 1);
            echo_str += _dict.count(word) ? _dict[word] : "未知单词";
            echo_str += " ";
        } while (i != std::string::npos);
        return echo_str;
    }

    ~Dict()
    {
    }

private:
    std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};